<template>
    <main>
        <header>
            <h1>{{ name }}</h1>
            <ul>
                <li v-if="userInfo.student_number">学号：{{ userInfo.student_number }}</li>
                <li>姓名：{{ userInfo.username }}</li>
                <li class="btn" @click="() => $router.back()">返回 》</li>
            </ul>
        </header>
        <section>
            <div class="report-form">
                <ul class="outline">
                    <el-empty v-if="!outline.length" :image-size="100" description="暂无数据"
                        style="margin: 0 auto;margin-top: 40px;" />
                    <li v-for="(item, idx) in outline" :key="idx" :class="item.className">
                        <div @click="handleTabClick(_item, idx)" v-for="_item in item.tabs"
                            :class="{ active: activeId == _item.options.name }">
                            <img src="" alt="">
                            <span>{{ _item.options.label }} </span>
                        </div>
                    </li>
                </ul>
                <div class="content" v-loading="loading">
                    <div class="table">
                        <el-empty description="数据格式异常" v-show="isError"/>
                        <v-form-render v-show="!isError" :form-json="formJson" :form-data="formData" :option-data="optionData"
                            ref="vFormRef">
                        </v-form-render>
                        
                        <!-- {{ content }} -->
                        <!-- <v-form-designer></v-form-designer> -->
                    </div>
                    <footer v-if="mode != 'preview'">
                        <template v-if="mode != 'correct'">
                            <div class="btn save" @click="save">保存</div>
                            <div class="btn submit" @click="submit">提交</div>
                        </template>
                        <template v-else>
                            <input class="input" v-model="score" type="text" placeholder="请输入成绩…">
                            <div class="collect" @click="toggleCollect">
                                <img style="cursor: pointer;width: 22px;" src="@/assets/tuxingbiaozhu@2x.png"
                                    v-if="isCollect" />
                                <img style="cursor: pointer;width: 22px;" src="@/assets/gary_star.png" v-else />
                                <span>收藏</span>
                            </div>
                            <div class="saveBtn" @click="handleCorrectScore">保存成绩</div>
                        </template>
                    </footer>
                </div>
            </div>
        </section>
    </main>
</template>
<script setup>
import { ElMessage, ElMessageBox } from 'element-plus'

import { ref, computed, reactive, onMounted, nextTick } from 'vue'
import { useRoute, useRouter } from 'vue-router';
import request from '@/request';
import { useAuthStore } from '@/stores/authStore';
import { storeToRefs } from 'pinia'; // 导入 storeToRefs 
const authStore = useAuthStore();
const { userInfo } = storeToRefs(authStore); // 使用 storeToRefs 解构 
const route = useRoute();
const router = useRouter();
const name = ref({})
const optionData = reactive({})
const vFormRef = ref(null)
const loading = ref(false)
const outline = ref([])
const activeId = ref([])
const formJson = reactive({})
const formData = reactive({})
const isCollect = ref(false)
const score = ref("")
const mode = ref("")
const isError = ref(false)
onMounted(async () => {
    loading.value = true
    mode.value = route.query.mode || ""
    isCollect.value = +route.query.isCollect
    name.value = route.query.name || ""
    await getReportDetail()
    getReportFormData()
    // 预览模式
    if (["correct", "preview"].includes(mode.value)) {
        vFormRef.value.disableForm() 
    }

})
// 获取报告详情
const getReportDetail = async () => {
    let params = {
        id: route.query.templateId
    }
    const res = await request.get('/api/master/template/details', params);
    if (res.code == 1) {
        try {
            let className = ["blue", "green", "red", "yellow", "orange", "purple", "pink", "gray", "brown", "black"]
            vFormRef.value.setFormJson(res.data.content)
            let list = extractTabs(JSON.parse(res.data.content))
            outline.value = list.map((item, idx) => {
                return {
                    tabs: item.tabs.flat(),
                    className: className[idx]
                }
            })

            outline.value.forEach((item, idx) => {
                activeId.value = item.tabs[0].options.name
            })

            nextTick(() => {
                vFormRef.value.$el.querySelectorAll(".el-tabs").forEach((element, index) => {
                    element.addEventListener('click', (e) => {
                        activeId.value = e.target.id.slice(4)
                    })
                })

            })
        }
        catch (error) {
            ElMessage({
                type: "error",
                message: error,
            });
            isError.value = true
            loading.value = false
            console.log(error);
        }

    }
}
// 保存成绩
const handleCorrectScore = async () => {
    if (!score.value) {
        ElMessage({
            type: "error",
            message: "请输入成绩",
        });
        return
    }
    let params = {
        id: route.query.reportId,
        score: score.value
    } 
    const res = await request.post('/api/master/report/correct_score', params);
    if (res.code == 1) {
        ElMessage({
            type: "success",
            message: res.msg,
        });
    }
}
const extractTabs = (data) => {
    let tabs = [];

    function traverse(widgetList) {
        for (let widget of widgetList) {
            if (widget.type === "tab") {
                tabs.push(widget);
            }
            if (widget.widgetList && widget.widgetList.length > 0) {
                traverse(widget.widgetList);
            }
            if (widget.tabs && widget.tabs.length > 0) {
                traverse(widget.tabs);
            }
        }
    }

    if (data.widgetList) {
        traverse(data.widgetList);
    }

    return tabs;
}
// 切换收藏
const toggleCollect = async () => {
    try {
        const res = await request.post("/api/master/report/collect", { id: route.query.reportId });
        if (res.code == 1) {
            isCollect.value = !isCollect.value;
            ElMessage({
                type: "success",
                message: res.msg,
            });
            //   updateData();
        }
    } catch (error) {
    } finally {
    }
};

// 切换tab
const handleTabClick = (item, idx) => {
    // 前置空值校验 
    if (!vFormRef.value?.$el || !item?.options?.name) return;

    const tabs = vFormRef.value.$el.querySelectorAll(".el-tabs");
    if (idx < 0 || idx >= tabs.length) return;

    // 合并选择器，避免链式查询报错 
    const targetTab = tabs[idx].querySelector(`#tab-${item.options.name}`);
    targetTab?.click();
}
// 获取报告数据
const getReportFormData = async () => {
    if (!route.query.reportId) {
        loading.value = false
        return
    }
    let params = {
        id: route.query.reportId
    }
    const res = await request.get('/api/master/report/details', params);
    console.log(res);

    if (res.code == 1) {
       try {
            let formData = JSON.parse(res.data.content)
            vFormRef.value.setFormData(formData)
            loading.value = false
        } catch (error) {
            ElMessage({
                type: "error",
                message: error,
            });
            isError.value = true
            loading.value = false
        }
    }
}
// 保存
/**
 * @param {*} submit_status 0 保存 1 提交
 */
const save = () => {
    // ElMessageBox.alert('确定保存报告', '提示', {
    //     confirmButtonText: 'OK',
    //     callback: () => {
    //     },
    // })
    submitReportRequest(0)
}
// 提交
/**
 * @param {*} submit_status 0 保存 1 提交
 */
const submit = () => {
    ElMessageBox.alert('确定提交报告', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        showCancelButton: true,
        callback: (action) => {
            if (action == 'cancel') {
                return
            }
            submitReportRequest(1)
        },
    })
}
// 提交报告
/**
 * @param {*} submit_status 0 保存 1 提交
 */
const submitReportRequest = async (submit_status) => {
    vFormRef.value.getFormData().then(async formData => {
        let params = {
            template_id: route.query.templateId,
            submit_status,
            content: JSON.stringify(formData)
        }
        const res = await request.post('/api/master/report/save_report', params);
        if (res.code == 1) {
            ElMessage.success(submit_status == 0 ? '保存成功' : '提交成功')
            if (submit_status == 1) {
                router.back()
            }
        }
    }).catch(error => {
        console.log(error);

        ElMessage.error(error.msg)
    })

}
</script>
<style lang="less" scoped>
header {
    width: 100%;
    height: 80px;
    background: #FFFFFF;
    box-shadow: 0px 0px 11px 0px rgba(70, 70, 163, 0.14);
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 15.6%;
    box-sizing: border-box;
    position: sticky;
    top: 0;
    z-index: 10;

    h1 {
        font-size: 24px;
        color: #333;
        font-weight: bold;
    }

    ul {
        display: flex;
        align-items: center;
        gap: 20px;
        font-size: 16px;
        color: #333333;

        .btn {
            width: 116px;
            line-height: 32px;
            text-align: center;
            background: #FFFFFF;
            border-radius: 16px;
            border: 1px solid #1343F5;
            cursor: pointer;
            color: #1343F5;
        }
    }
}

section {
    height: calc(100vh - 80px);
    box-sizing: border-box;
    overflow-y: auto;
    background: #F7F9FD;
    padding: 40px 15.6%;
}

.report-form {
    display: flex;
    gap: 20px;

    .outline {
        width: 200px;
        height: auto;
        /* 高度根据内容自动调整 */
        max-height: 349px;
        /* 限制最大高度 */
        overflow-y: auto;
        /* 内容超出时显示滚动条 */
        background: #FFFFFF;
        display: block;
        box-shadow: 0px 0px 11px 0px rgba(70, 70, 163, 0.14);
        border-radius: 8px;
        top: 0;
        position: sticky;
        z-index: 10;

        li {
            div {
                padding: 10px 16px;
                border-bottom: solid 1px rgba(230, 230, 230, 0.5);
                font-size: 16px;
                color: #666666;
                cursor: pointer;

                &:last-child {
                    // border-bottom: none;
                }
            }
        }

        .blue {
            .active {
                &::before {
                    background: #2D53F8;
                }
            }
        }

        .green {
            .active {
                &::before {
                    background: #3FBA3C;
                }
            }
        }

        .red {
            .active {
                &::before {
                    background: #C13030;
                }
            }
        }

        .active {
            position: relative;

            &::before {
                content: "";
                width: 4px;
                height: 100%;
                background: #2D53F8;
                display: block;
                position: absolute;
                left: 0;
                top: 0;
            }
        }
    }

    .content {
        width: calc(100% - 200px);
        height: calc(100vh - 200px);
        // max-width: 1080px;
        box-shadow: 0px 0px 11px 0px rgba(70, 70, 163, 0.14);
        background-color: #fff;
        border-radius: 8px;
        // padding: 20px;
        box-sizing: border-box;
        padding-bottom: 40px;

        // padding: 20px;
        .table {
            border: solid #ccc 1px;
            height: calc(100vh - 240px);
            overflow-y: auto;
            margin: 20px;
            margin-bottom: 20px;
            word-break: break-all;
            padding: 20px;
            box-sizing: border-box;
        }

        footer {
            display: flex;
            justify-content: flex-end;
            gap: 20px;
            // position: sticky;
            // top: calc(100vh - 1px);
            height: 80px;
            padding: 0px;
            padding-left: 20px;
            box-sizing: border-box;
            align-items: center;
            padding-bottom: 0;
            background-color: #fff;
            padding-right: 20px;
            z-index: 100;
            box-shadow: 0px 0px 10px 0px rgba(0, 0, 0, 0.1);

            .input {
                height: 50px;
                flex: 1;
                background: rgba(45, 83, 248, 0.03);
                border-radius: 4px;
                border: 1px solid rgba(45, 83, 248, 0.43);
                padding-left: 20px;
            }

            .collect {
                width: 120px;
                height: 40px;
                font-size: 14px;
                background: rgba(45, 83, 248, 0);
                border-radius: 20px;
                border: 1px solid rgba(19, 67, 245, 0.07);
                display: flex;
                justify-content: center;
                align-items: center;
                font-size: 16px;
                color: #333333;
                gap: 6px;
                cursor: pointer;
            }

            .saveBtn {
                width: 120px;
                height: 40px;
                background: #2D53F8;
                border-radius: 20px;
                display: flex;
                align-items: center;
                justify-content: center;
                color: #fff;
                font-size: 16px;
                border: 1px solid #1343F5;
                cursor: pointer;
            }

            .btn {
                width: 120px;
                height: 40px;
                border-radius: 40px;
                font-size: 16px;
                color: #fff;
                cursor: pointer;
                text-align: center;
                line-height: 40px;
            }

            .save {
                // background-color: #2D53F8;
                color: #2D53F8;
                border: solid #2D53F8 1px;
            }

            .submit {
                background-color: #2D53F8;
            }
        }
    }
}
</style>
<style lang="less">
main {
    .table-cell {
        border: solid rgb(128, 128, 128) 1px !important;
        // padding: 12px 12px;

        .static-content-item {
            padding: 12px 12px;
            background-color: rgb(246, 246, 246);
        }

        .el-form-item--default {
            margin-bottom: 0;
        }

        .el-input__wrapper {
            box-shadow: none !important;
            padding: 0;
        }

        .el-input__wrapper:hover {
            box-shadow: none;
        }

        .el-form-item__label {
            display: none;
        }

        .el-input__suffix {
            display: none;
        }

        .el-row {
            align-items: center;
        }
    }
}
</style>